package com.googlecode.sqldatagenerator.applet;

import java.applet.Applet;
import java.awt.Color;
import java.net.MalformedURLException;
import java.net.URL;

import com.googlecode.sqldatagenerator.exception.SqlParseException;
import com.googlecode.sqldatagenerator.model.dto.ConnectionDto;
import com.googlecode.sqldatagenerator.model.dto.GeneratorRequestDto;
import com.googlecode.sqldatagenerator.model.dto.GeneratorResponseDto;
import com.googlecode.sqldatagenerator.util.Callback;
import com.googlecode.sqldatagenerator.util.JsonUtil;

/**
 * @author wellsantos@wellsantos.com
 */
public class SqlDataGeneratorApplet extends Applet {

    private static final long serialVersionUID = 342694064478397521L;
    
    public SqlDataGeneratorApplet() {
        setBackground(Color.BLUE);
    }

    public synchronized void generateScript(String databaseDriver, String databaseUrl, String userName, String password, String sqlStatement) {        
        ConnectionDto connection = new ConnectionDto();
        connection.setDatabaseUrl(databaseUrl);
        connection.setUserName(userName);
        connection.setPassword(password);
        
        GeneratorRequestDto request = new GeneratorRequestDto();
        request.setSqlStatement(sqlStatement);
        
        System.out.println(connection);
        System.out.println(request);
        
        Callback<GeneratorResponseDto> callback = new Callback<GeneratorResponseDto>() {
            
            @Override
            public void onSuccess(GeneratorResponseDto result) {
                runJavascript("callback.onSuccess(" + JsonUtil.toJson(result) + ")");
            }
            
            @Override
            public void onError(Exception ex) {
                runJavascript("callback.onError(" + JsonUtil.toJson(ex.getMessage()) + ")");
            }
        };
        
        callback.onError(new SqlParseException("Hello", 1, 1, 1));
    }

    public void runJavascript(String expr){
        try {
            SqlDataGeneratorApplet.this.getAppletContext().showDocument(new URL("javascript:" + expr));
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

}
